import React, { useState, useEffect, useRef } from 'react'
import { Popconfirm, Button, Modal, Form, Radio, Tag, message, Tooltip } from 'antd';
import { CheckCircleOutlined, CloseCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { connect } from 'dva';
import { ProTable } from '@ant-design/pro-components';

const CommentManage = ({ commentList, dispatch, userInfo }) => {
  useEffect(() => {
    tableRef.current?.reload()// 刷新表格
  }, [commentList])
  const userType = userInfo.userType
  const tableRef = useRef();
  const [commentViewStatus, setCommentViewStatus] = useState(false)
  const [commentData, setCommentData] = useState([])
  const [isModal, setIsModal] = useState(false)// 控制弹窗显与隐
  const [editForm] = Form.useForm();
  const [formData, setFormData] = useState({})
  const statusFilters = [
    { text: '待审核', value: 0 },
    { text: '已通过', value: 1 },
    { text: '不通过', value: 2 },
  ];
  const columns = [
    userType === 0 && {
      title: '评论id', dataIndex: 'commentId', key: 'commentId', align: 'center', search: false,
      sorter: (a, b) => a.commentId - b.commentId
    },
    userType === 0 && { title: '评论人昵称', dataIndex: 'displayName', key: 'displayName', align: 'center', },
    { title: '评论内容', dataIndex: 'content', key: 'content', align: 'center', ellipsis: true, },
    {
      title: '评论时间', dataIndex: 'createTime', key: 'createTime', align: 'center',
      sorter: (a, b) => new Date(a.createTime) - new Date(b.createTime)
    },
    userType !== 0 && {
      title: '获赞数', dataIndex: 'like', key: 'like', align: 'center', search: false,
      sorter: (a, b) => a.like - b.like
    },
    userType !== 0 && {
      title: '反对数', dataIndex: 'disLike', key: 'disLike', align: 'center', search: false,
      sorter: (a, b) => a.disLike - b.disLike
    },
    { title: '文章标题', dataIndex: 'articleTitle', key: 'articleTitle', align: 'center', ellipsis: true, },
    { title: '文章作者', dataIndex: 'authorDisplayName', key: 'authorDisplayName', align: 'center', },

    {
      title: '评论状态', dataIndex: 'status', key: 'status', align: 'center', search: false,
      sorter: (a, b) => a.status - b.status,
      filters: statusFilters,
      onFilter: (value, record) => record.status === value,
      render: (_, record) => viewStatus(record)
    },
    {
      title: '操作', key: 'commentInfo', align: 'center', search: false,
      render: (_, record) => (
        <>
          <Button type='link' key="view" onClick={() =>
            handleDisplayArticle(record)}>{record.status === 0 && userType === 0 ? '审核' : '详情'}</Button>
          <Popconfirm title="确定要删除该评论吗？"
            key="delect1"
            onConfirm={() => {
              dispatch({
                type: 'commentManage/delComment',
                payload: {
                  commentId: record.commentId,
                },
              })
            }} okText="确定" cancelText="取消">
            <Button danger type='link' key="delect">删除</Button>
          </Popconfirm>
        </>
      ),
    },
  ].filter(Boolean);

  const viewStatus = ({ status }) => {
    switch (status) {
      case 0:
        return <Tag key="0" icon={<ExclamationCircleOutlined />} color='warning'>待审核</Tag>;
      case 1:
        return <Tag key="1" icon={<CheckCircleOutlined />} color='success'>已通过</Tag>;
      default:
        return <Tag key="2" icon={<CloseCircleOutlined />} color='error'>不通过</Tag>;
    }
  }

  const handleDisplayArticle = (data) => {
    setCommentData(data);
    setCommentViewStatus(data.status === 0 ? true : false);
    setIsModal(true);
    editForm?.setFieldsValue({
      status: data.status,
    });
    setFormData(data)
  }

  const reviewComment = (values) => {
    if (values.status === commentData.status) {
      message.error("请选择审核意见")
      return;
    }
    dispatch({
      type: 'commentManage/reviewComment',
      payload: {
        commentIds: [formData.commentId],
        status: values.status,
      },
    });
    setIsModal(false)
  }

  const reloadTable = () => {
    dispatch({
      type: 'commentManage/queryComment',
    })
  }

  return <>
    <ProTable actionRef={tableRef} defaultData={commentList} columns={columns} key="commentList"
      pagination={{
        defaultPageSize: 10, // 默认每页显示10条数据
        showSizeChanger: true, // 显示每页显示条数的选择器
        pageSizeOptions: ['10', '20', '50'], // 可供用户选择的每页显示条数选项
      }}
      options={{ reload: reloadTable, setting: true, density: true, }}
      toolBarRender={() => [<>{userType === 0 && <Tooltip title="该按钮可以通过全部未审核的评论"><Button key="reviewAllArticle" type="primary" onClick={() => {
        dispatch({
          type: 'commentManage/reviewAllComment',
        });
      }}>一键审核</Button></Tooltip>}</>]}
      request={(params, sort, filter) => {
        return Promise.resolve({
          data: () => {
            return commentList?.filter((item) => {
              let result = true;
              Object.entries(params).forEach(([key, value]) => {
                if (key == "current" || key == "pageSize") {
                  return;
                }
                const dataKey = key.replace("search", "")
                if (item.hasOwnProperty(dataKey)) {
                  result = (result && item[dataKey].indexOf(value) != -1)
                }
              })
              return result;
            });
          },
          success: true,
        });
      }} />;
    <Modal key="commentInfo" title={userType === 0 ? "评论详情" : "我的评论"} open={isModal} onCancel={() => setIsModal(false)} maskClosable={false}
      footer={[
        userType === 0 && commentViewStatus ? <><Button key="submit" type="primary" onClick={() => { editForm?.submit(); }}>确定</Button>
          <Button key="back" onClick={() => setIsModal(false)}>取消</Button></> :
          <Button key="close" onClick={() => setIsModal(false)}>关闭</Button>
      ]}>
      <Form form={editForm} name="basic" labelCol={{ span: 8, }}
        wrapperCol={{ span: 24, }} style={{ width: "60%" }} onFinish={reviewComment}>
        <Form.Item label="文章标题" name="articleTitle">{commentData.articleTitle}</Form.Item>
        <Form.Item label="作者" name="authorDisplayName">{commentData.authorDisplayName}</Form.Item>
        {userType === 0 && <Form.Item label="评论人:" name="displayName">{commentData.displayName}</Form.Item>}
        <Form.Item label="评论内容:" name="content" >{commentData.content}</Form.Item>
        {userType === 0 && !commentViewStatus && <Form.Item label="获赞数" name="like">{commentData.status === 1 ? commentData.like : '暂无'}</Form.Item>}
        {userType === 0 && !commentViewStatus && <Form.Item label="反对数" name="disLike">{commentData.status === 1 ? commentData.disLike : '暂无'}</Form.Item>}
        <Form.Item label="评论时间" name="createTime">{commentData.createTime}</Form.Item>
        {userType === 0 && commentViewStatus && <Form.Item label="审核意见" name='status' rules={[{ required: true, message: '请选择审核状态' }]} >
          <Radio.Group options={[{ label: "通过", value: 1 }, { label: "不通过", value: 2 }]} />
        </Form.Item>}
      </Form>
    </Modal >
  </>
}

export default connect(({ commentManage, user }) => ({
  commentList: commentManage.commentList,
  userInfo: user.userInfo,
}))(CommentManage);